package com.xin.data.simbapesa.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatActivity.RESULT_OK

class ContactHelper(
    private val baseCType: AppCompatActivity
) {
    private val contactLauncherCType =
        baseCType.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it == null || it.resultCode != RESULT_OK) {
                tempContactCbCType?.invoke("", "",false)
            } else {
                it.data?.data?.let { uri ->
                    pickContactBType(uri)
                }
            }
        }
    private var tempContactCbCType: ((nameCType: String, phoneCType: String,isSucc:Boolean) -> Unit)? = null
    private var tempContactCbCTyp1: ((isPhone: Boolean) -> Unit)? = null

    fun pickContactBType(contactCbCType: (nameCType: String, phoneCType: String,isSucc:Boolean) -> Unit) {
        tempContactCbCType = contactCbCType
        contactLauncherCType.launch(
            Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
        )
    }

    fun pickContactBType1(context: Context, contactCbCType: (isPhone: Boolean) -> Unit) {
        tempContactCbCTyp1 = contactCbCType
        val pickContactIntent = Intent(Intent.ACTION_PICK).apply {
            type = ContactsContract.Contacts.CONTENT_TYPE
        }
        if (pickContactIntent.resolveActivity(context.packageManager) != null) {
            pickContactBType1(true)
        } else {
            pickContactBType1(false)
        }
    }

    private fun pickContactBType1(isPhone: Boolean) {
        tempContactCbCTyp1?.invoke(isPhone)
    }

    private fun pickContactBType(uriCType: Uri) {
        var nameCType = ""
        var phoneCType = ""

        val projectionCType = arrayOf(
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        )
        baseCType.contentResolver.query(
            uriCType, projectionCType, null, null, null
        )?.use {
            if (it.moveToFirst()) {
                val namePosCType =
                    it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                nameCType =
                    if (namePosCType == -1 || it.isNull(namePosCType)) ""
                    else it.getString(namePosCType)
                val phonePosCType =
                    it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                phoneCType =
                    if (phonePosCType == -1 || it.isNull(phonePosCType)) ""
                    else it.getString(phonePosCType)
            }
        }
        tempContactCbCType?.invoke(nameCType, phoneCType,true)
    }
}